package org.flown.util;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.concurrent.Executors;


public class HTTPClientUtil
{
    private static final HttpClient client = HttpClient.newBuilder()
            .version(HttpClient.Version.HTTP_2)
            .executor(Executors.newFixedThreadPool(3))
            .build();


    public static URI buildGetURI(String url, HashMap<String, String> parameters)
    {
        StringBuilder builder_uri = new StringBuilder(url);
        if (parameters == null || parameters.isEmpty())
            return URI.create(url);
        builder_uri.append("?");
        for (String key : parameters.keySet())
            builder_uri.append(key).append("=").append(parameters.get(key)).append("&");
        builder_uri.deleteCharAt(builder_uri.length() - 1);
        return URI.create(builder_uri.toString());
    }

    public static HttpResponse<String> GET(String url, HashMap<String, String> parameters)
            throws IOException, InterruptedException
    {
        HttpRequest request = HttpRequest.newBuilder(HTTPClientUtil.buildGetURI(url, parameters))
                .version(HttpClient.Version.HTTP_2)
                .GET()
                .build();
        return HTTPClientUtil.client.send(request, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
    }

}





